package com.sunmouse.toolkit.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunmouse.toollib.adapter.BasicAdapter;
import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.bean.MessageBean;

import java.util.List;


/**
 * Created by Administrator on 2017/9/25 0025.
 */
public class MessageAdapter extends BasicAdapter<MessageAdapter.ViewHolder, MessageBean> {

    private MessageBean bean;
    private int key = 3;

    public MessageAdapter(List<MessageBean> list, Context context) {
        super(list, context);
    }

    @Override
    protected View bindView(LayoutInflater inflater, ViewGroup parent, Context context, List<MessageBean> list, int position) {
        bean = list.get(position);
        View v;
        if (bean.getFrom() == MessageBean.From.ME) {
            v = inflater.inflate(R.layout.adapter_msg_me, parent, false);
        } else {
            v = inflater.inflate(R.layout.adapter_msg_you, parent, false);
        }
        v.setTag(R.string.layout_key, bean.getFrom());
        return v;
    }

    @Override
    protected ViewHolder bindViewHolder(View cv, ViewGroup parent, Context context) {
        return new ViewHolder(cv);
    }

    @Override
    protected void bindData(ViewHolder vh, int position, List<MessageBean> list, Context context) {
        bean = list.get(position);
        vh.dateTv.setText(bean.getTime());
        vh.msgTv.setText("\t\t\t\t"+bean.getMsg());
        vh.avatarIv.setImageResource(R.mipmap.ic_launcher);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
//        LogUtils.d("----------parent="+parent.getClass().hashCode());

        if (convertView == null) return super.getView(position, convertView, parent);

        MessageBean.From from = (MessageBean.From) convertView.getTag(R.string.layout_key);
        if (from == list.get(position).getFrom()) {
            return super.getView(position, convertView, parent);
        }
        convertView = bindView(inflater, parent, context, list, position);
        ViewHolder vh = bindViewHolder(convertView, parent, context);
        convertView.setTag(vh);
        bindData(vh, position, list, context);
        return convertView;

    }

    static class ViewHolder extends BasicAdapter.ViewHolder {
        TextView dateTv;
        TextView msgTv;
        ImageView avatarIv;

        public ViewHolder(View v) {
            super(v);
            this.dateTv = (TextView) v.findViewById(R.id.date_tv);
            this.msgTv = (TextView) v.findViewById(R.id.msg_tv);
            this.avatarIv = (ImageView) v.findViewById(R.id.avatar_iv);
        }
    }
}
